package com.supostacks.xuetangerp.controller;

import cn.dev33.satoken.util.SaResult;
import com.alibaba.fastjson.JSONObject;
import com.supostacks.rpc.server.dto.BaseDto;
import com.supostacks.rpc.server.dto.FileManagementDto;
import com.supostacks.rpc.server.req.DeployReq;
import com.supostacks.rpc.server.res.XResult;
import com.supostacks.xuetangerp.server.oss.AliyunServer;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RequestMapping("/oss")
@RestController
public class OSSController extends BaseController {

    private final AliyunServer aliyunServer = new AliyunServer();

    @PostMapping("/upload/file")
    public SaResult uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam("source") String source,
            @RequestParam("fileType") String fileType) {

        String originalFilename = file.getOriginalFilename();
        String objectName = source + "/" + originalFilename;

        try {
            aliyunServer.putObject(file.getInputStream(), objectName);

            FileManagementDto fileManagement = FileManagementDto.builder().
                    fileType(fileType).
                    fileKey(objectName).
                    build();

            DeployReq req = DeployReq.builder().data(fileManagement)
                    .type("insert").build();
            XResult res = dataDeployService.deploy(req);

            Object result = res.getResult();
            String url = aliyunServer.getObject(objectName);

            JSONObject json = new JSONObject();
            json.put("imageUrl", url);
            json.put("fileId", result);

            return SaResult.ok().setData(json);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


    @Override
    public BaseDto buildData(JSONObject json) {
        return JSONObject.toJavaObject(json, FileManagementDto.class);
    }

    @Override
    public BaseDto takeBaseDto() {
        return new FileManagementDto();
    }
}
